<template>
  <div class="cyber-task-detail">
    <Notification ref="notification" />

    <!-- 科技感标题 -->
    <div class="cyber-header">
      <div class="hologram-line"></div>
      <h1 class="neon-title">
        <a :href="`/clusters/${appId}`" class="task-id">返回</a>
        聚类分析
      </h1>
      <div class="hologram-line"></div>
    </div>

    <div class="cyber-content">
      <!-- 横向柱状图区域 -->
      <div class="cyber-section">
        <div class="section-header">
          <div class="pulse-dot"></div>
          <h2 class="section-title">问题分布</h2>
          <div class="tech-border"></div>
        </div>

        <div class="horizontal-bars-container">
          <div
              v-for="item in barChartData"
              :key="item.label"
              class="bar-row"
              :class="{ active: selectedLabel === item.label }"
              @click="handleBarClick(item.label)"
          >
            <div class="bar-label">{{ item.label }}</div>
            <div class="bar-track">
              <div
                  class="cyber-bar"
                  :style="{ width: getBarWidth(item.count) + '%' }"
                  :data-count="item.count"
              >
                <div class="bar-glow"></div>
                <div class="bar-pulse"></div>
                <div class="bar-value">{{ item.count }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 词云图区域 -->
      <div class="cyber-section" v-if="showWordCloud">
        <div class="section-header">
          <div class="pulse-dot"></div>
          <h2 class="section-title">词云 - 标签 {{ selectedLabel }}</h2>
          <div class="tech-border"></div>
        </div>

        <div class="wordcloud-hologram" ref="wordcloudContainer">
          <div class="hologram-grid"></div>
          <div class="hologram-scan"></div>
          <div ref="wordcloudSvg" class="cyber-wordcloud"></div>
        </div>
      </div>
    </div>

    <!-- 问题列表全息投影 -->
    <div v-if="showQuestionModal" class="hologram-modal" @click="closeQuestionModal">
      <div class="hologram-content" @click.stop>
        <div class="modal-header">
          <div class="data-stream"></div>
          <h3 class="neon-text">包含 "{{ selectedWord }}" 的问题：</h3>
          <button class="cyber-close" @click="closeQuestionModal">
            <span class="close-icon">✕</span>
          </button>
        </div>
        <div class="question-scroll">
          <div
              v-for="(question, index) in selectedQuestions"
              :key="index"
              class="cyber-question"
              :style="{ '--delay': index * 0.1 + 's' }"
          >
            <div class="question-index">{{ index + 1 }}</div>
            <div class="question-text">{{ question }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 背景科技元素 -->
    <div class="cyber-bg-elements">
      <div class="grid-lines"></div>
      <div class="floating-orbs">
        <div class="orb orb-1"></div>
        <div class="orb orb-2"></div>
        <div class="orb orb-3"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import Notification from "@/components/Notification.vue"
import { useRoute } from 'vue-router'
import * as d3 from 'd3'
import cloud from 'd3-cloud'

const route = useRoute()
const appId = route.params.app_id
const taskId = route.params.task_id

const notification = ref(null)
const wordcloudSvg = ref(null)
const wordcloudContainer = ref(null)
const showWordCloud = ref(false)
const showQuestionModal = ref(false)
const selectedLabel = ref(null)
const selectedWord = ref('')
const selectedQuestions = ref([])

const barChartData = ref([])
const wordCloudData = ref([])
const maxCount = ref(0)

const BASE_URL = 'http://localhost:5000'

onMounted(() => {
  fetchBarChartData()
})

const fetchBarChartData = async () => {
  try {
    const response = await fetch(`${BASE_URL}/tasks/word-bar`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        app_id: appId,
        task_id: taskId
      })
    })

    if (!response.ok) throw new Error('获取柱状图数据失败')

    const data = await response.json()
    const dataArray = Object.entries(data).map(([label, count]) => ({
      label,
      count: parseInt(count)
    })).sort((a, b) => b.count - a.count)

    barChartData.value = dataArray
    maxCount.value = Math.max(...dataArray.map(item => item.count))

  } catch (error) {
    console.error('Error:', error)
    notification.value?.showNotificationMessage('获取数据失败', 'error')
  }
}

const getBarWidth = (count) => {
  return (count / maxCount.value) * 100
}

const handleBarClick = async (label) => {
  try {
    selectedLabel.value = label
    showWordCloud.value = false

    // 投影仪动画效果
    if (wordcloudContainer.value) {
      wordcloudContainer.value.classList.add('hologram-activate')
    }

    const response = await fetch(`${BASE_URL}/word_cloud/cluster_word_cloud`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        app_id: appId,
        task_id: taskId,
        label: parseInt(label)
      })
    })

    if (!response.ok) throw new Error('获取词云数据失败')

    const data = await response.json()
    wordCloudData.value = data

    setTimeout(() => {
      showWordCloud.value = true
      nextTick(() => {
        if (wordcloudContainer.value) {
          wordcloudContainer.value.classList.remove('hologram-activate')
        }
        drawCyberWordCloud(data.word_freq, data.word2questions)
      })
    }, 800)

  } catch (error) {
    console.error('Error:', error)
    notification.value?.showNotificationMessage('获取词云数据失败', 'error')
  }
}

const drawCyberWordCloud = (wordFreq, word2questions) => {
  const container = wordcloudSvg.value
  if (!container) return

  container.innerHTML = ''

  const width = 800
  const height = 500

  const svg = d3.select(container)
      .append('svg')
      .attr('width', width)
      .attr('height', height)
      .append('g')
      .attr('transform', `translate(${width / 2},${height / 2})`)

  const colors = ['#00ffff', '#ff00ff', '#ffff00', '#00ff00', '#ff0066']
  const glows = ['0 0 10px #00ffff', '0 0 10px #ff00ff', '0 0 10px #ffff00', '0 0 10px #00ff00', '0 0 10px #ff0066']

  const layout = cloud()
      .size([width, height])
      .words(Object.entries(wordFreq).map(([text, value]) => ({
        text,
        size: Math.log(value) * 15 + 20,
        value,
        color: colors[Math.floor(Math.random() * colors.length)],
        glow: glows[Math.floor(Math.random() * glows.length)]
      })))
      .padding(8)
      .rotate(() => ~~(Math.random() * 3) * 30 - 30)
      .fontSize(d => d.size)
      .on('end', draw)

  layout.start()

  function draw(words) {
    const text = svg.selectAll('text')
        .data(words)
        .enter()
        .append('text')
        .style('font-size', d => `${d.size}px`)
        .style('fill', d => d.color)
        .style('filter', d => d.glow)
        .style('font-family', 'Courier New, monospace')
        .style('font-weight', 'bold')
        .attr('text-anchor', 'middle')
        .attr('transform', d => `translate(${d.x},${d.y})rotate(${d.rotate})`)
        .text(d => d.text)
        .style('cursor', 'pointer')
        .style('opacity', 0)
        .on('click', (event, d) => {
          handleWordClick(d.text, word2questions[d.text] || [])
        })

    text.transition()
        .duration(1000)
        .style('opacity', 1)
  }
}

const handleWordClick = (word, questions) => {
  selectedWord.value = word
  selectedQuestions.value = questions
  showQuestionModal.value = true
}

const closeQuestionModal = () => {
  showQuestionModal.value = false
  selectedWord.value = ''
  selectedQuestions.value = []
}
</script>

<style src="@/assets/styles/task-detail.css" scoped>
</style>